package com.fld.fldcodemother.aop;

import com.fld.fldcodemother.annotation.AuthCheck;
import com.fld.fldcodemother.exception.BusinessException;
import com.fld.fldcodemother.exception.ErrorCode;
import com.fld.fldcodemother.model.entity.User;
import com.fld.fldcodemother.model.enums.UserRoleEnum;
import com.fld.fldcodemother.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 *  权限校验切面
 */
@Aspect // 切面类
@Component // 自动注入 容器实例
public class AuthInterceptor {

    @Autowired
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor (ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 该方法上标识的注解的参数的值
        String mustRole = authCheck.mustRole();

        // 通过静态方法获得请求属性
        RequestAttributes currentRequestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) currentRequestAttributes).getRequest();

        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum= UserRoleEnum.getEnumByValue(mustRole);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }

        // 必须有该权限才能通过
        // 获取当前用户具有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnum == null ) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 要求必须有管理员权限，但用户没有管理员权限，拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        return joinPoint.proceed();
    }
}
